package codec

import (
	"app/common/constant"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gookit/validate"
	"github.com/gookit/validate/locales/zhcn"
)

func JsonDecodeRequest[T any]() func(context.Context, *http.Request) (request interface{}, err error) {
	var req T
	return func(ctx context.Context, r *http.Request) (interface{}, error) {
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
			return nil, constant.NewError(constant.LogicError, err.Error())
		}
		//验证器验证
		//注册中文翻译
		v := validate.Struct(req)
		zhcn.Register(v)
		if v.Validate() {
			return req, nil
		} else {
			return nil, constant.NewError(constant.LogicError, v.Errors.One())
		}
	}
}

// 统一返回json
func JsonEncodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
	return json.NewEncoder(w).Encode(response)
}

func GinBind[T any](c *gin.Context, target *T) (err error) {
	err = c.ShouldBind(target)
	if err != nil {
		return err
	}
	// validate.AddValidators(validate.M{
	// 	"required_if_custom": func(val interface{}, kvs ...string) bool {
	// 		fmt.Printf("%s", "required_if_custom")
	// 		fmt.Printf("%+v", val)
	// 		fmt.Printf("%+v", kvs)
	// 		return false
	// 	},
	// })
	//验证器验证
	v := validate.Struct(target)
	//注册中文翻译
	zhcn.Register(v)
	if !v.Validate() {
		err = fmt.Errorf(v.Errors.One())
	}
	return
}
